import Taro from '@tarojs/taro'
import loginStore from '../store/login'

// 请求封装
export function http(options) {
  const {url,data,method} = options
  // 获取 token
  let token = loginStore.token
  return new Promise((resolve,reject) => {
    Taro.request({
      method: method,
      url: url,
      data: data,
      header: {
        'token': token
      },
      success: (respData) => {
        console.log('请求得到的所有数据: ', respData)
        switch(respData.statusCode) {
          case 200: //请求成功
            respData.header.token && setStorage('token',respData.header.token)
            resolve(respData.data)
            break;
          case 401: //没有权限
            // resolve(respData.data)
            Taro.showToast({
              title: '您没有权限',
              mask: true,
              success: ()=>{
                Taro.navigateTo('/pages/login/login')
              }
            })
            break;
          case 500: //请求成功
            Taro.showToast({
              title: '服务器出错',
              mask: true
            })
            break;
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export function getStorage(key) {
    try {
      const value = Taro.getStorageSync(key)
      if(value) return value
    }
    catch(e) {
      console.log('e', e)
      return ''
    }
}

export function setStorage(key,value) {
  console.log('key', key)
    try {
      Taro.setStorageSync(key,value)
      console.info(key,":",value,'写入成功')
    }
    catch(e) {
      console.err(key, '写入失败 err:',e)
    }
}
